import axios from 'axios'
import Vue from 'vue'
import {Message, Loading} from 'element-ui'
import Cookies from 'js-cookie' 
import Utils from '@/libs/utils'
// import Router from '@/router'
var merge = require('webpack-merge')

axios.defaults.headers.post['Content-Type'] = 'application/json;charset=utf-8'; 
axios.defaults.withCredentials = true;
axios.interceptors.request.use(
  config =>{
    if(Cookies.get('x-token')){
      // 获取本地Cookies内容
      config.headers.common['X-Auth-Token'] = Cookies.get('x-token')
    }
    //加入每一个请求时，后台需要的一些，前端可以得到的Header内容
    //config.headers.common['URL'] = 'URL'
    
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

axios.interceptors.response.use(
  response => {
    //错误信息统一处理
    if(response.data.overdue) {
      Message.error('登录信息已失效')
      Utils.logout()
    }else {
      if(!response.data.success){
        if(response.data.errorMsg){
          Message.error(response.data.errorMsg)
          if(response.data.errorCode == 'CU_MSG_000009'){
            Utils.logout()
          }
        }// else{
        //   Message.error('网络异常，请稍后再试')
        // }
      }
    } 
    return response
  },
  error => {
    return Promise.reject(error)
  }
);

export default {
  install(Vue) {
      Vue.prototype.$umaHttp = axios
      Vue.umaHttp = axios
  },
  // $umaHttp: axios
}

export const $umaHttp = merge(axios);